package cn.hy.tiny.demo.core;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author huang.xy
 * @Description TODO
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Executor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        executor = new SimpleExecutor();
        return executor.query(configuration,configuration.getMapperStatementCache().get(statementId), params);
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        executor = new SimpleExecutor();
        List<Object> query = executor.query(configuration, configuration.getMapperStatementCache().get(statementId), params);
        if(query.size() == 1) {
            return (T) query.get(0);
        }
        throw new RuntimeException("too many result");
    }

    @Override
    public <T> T getMapper(Class<T> mapperClass) {
       return (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[] {mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String id = className +"."+ methodName;
                Type genericReturnType = method.getGenericReturnType();
                //判断是否实现泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    return selectList(id, args);
                }
                return selectOne(id, args);
            }
        });
    }

    @Override
    public void close() throws SQLException {
        if(executor != null) {
            executor.close();
        }
    }
}
